import diyStyle_mixins from './diyStyle_mixin.js'
import request from '../utils/request.js'
import store from '../store/index.js'


const mappings = {
	//主商城
	map_text: new Map([
		['--color_main', 'mainColor16'],
		['--color_main_bg', 'mainLinearColor'],
		['--color_main_chat_bg', 'mainLinearColor'],
		['--color_main_bg_zero', 'mainLinearColorZero'],
		['--color_vice', 'subColor16'],
		['--color_vice_bg', 'subLinearColor'],
		['--color_price', 'priceColor'],
	]),
	// 积分
	map_integral_text: new Map([
		['--color_integral_main', 'mainColor'],
		['--color_integral_price', 'mainColor'],
		['--color_integral_main_bg', 'mainLinearColor'],
		['--color_integral_vice', 'subColor'],
	]),
	// 推手
	map_extral_text: new Map([
		['--color_extral_main', 'mainColor'],
		['--color_extral_vice', 'subColor'],
		['--color_extral_main_bg', 'mainLinearColor'],
		['--color_extral_main_bgZero', 'mainLinearColorZero'],
	]),
	// 拼团
	map_spell_text: new Map([
		['--color_spell_main', 'mainColor'],
		['--color_spell_main_bg', 'mainLinearColor'],
		['--color_spell_vice', 'subColor'],
	]),
	// 预售
	map_presell_text: new Map([
		['--color_presell_main', 'mainColor'],
		['--color_presell_main_bg', 'mainLinearColor'],
		['--color_presell_vice', 'subColor'],
	]),
	// 阶梯团
	map_ladder_text: new Map([
		['--color_ladder_main', 'mainColor'],
		['--color_ladder_main_bg', 'mainLinearColor'],
		['--color_ladder_vice', 'subColor'],
	]),
	// 秒杀
	map_seckill_text: new Map([
		['--color_seckill_main', 'mainColor'],
		['--color_seckill_main_bg', 'mainLinearColor'],
		['--color_seckill_vice', 'subColor'],
		['--color_seckill_main_bg_zero', 'mainLinearColorZero'],
	]),
	// 优惠券
	map_coupon_text: new Map([
		['--color_coupon_main', 'mainColor'],
		['--color_coupon_opacity', 'mainOpacity'],
		['--color_coupon_main_bg', 'mainLinearColor'],
	]),
	// 短视频和直播部分
	map_video_text: new Map([
		['--color_video_main', 'mainColor'],
		['--color_video_main_vertical_bg', 'mainVerticalColor'],
		['--color_video_main_bg', 'mainLinearColor'],
	])
}

// 16进制颜色转换成rgb,用于 动态颜色转换
function set16ToRgb(str, op) {
	var reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
	if (!reg.test(str)) {
		return;
	}
	let newStr = (str.toLowerCase()).replace(/\#/g, '')
	let len = newStr.length;
	if (len == 3) {
		let t = ''
		for (var i = 0; i < len; i++) {
			t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
		}
		newStr = t
	}
	let arr = []; //将字符串分隔，两个两个的分隔
	for (var i = 0; i < 6; i = i + 2) {
		let s = newStr.slice(i, i + 2)
		arr.push(parseInt("0x" + s))
	}

	if (op !== undefined) {
		return `rgba(${arr.join(",")},${op})`;
	} else {
		return 'rgb(' + arr.join(",") + ')';
	}
}

//app：将tabbar网络图片变成本地图片
function getTabImgInfo(tab) {
	return Promise.all([
		['autoImg', tab.autoImg.img],
		['selectImg', tab.selectImg.img]
	].map(tar => {
		return new Promise((resolve, reject) => {
			if(tar[1]){
				uni.getImageInfo({
					src: tar[1],
					complete(cm) {
						if (cm.errMsg == 'getImageInfo:ok') {
							resolve({
								localPath: cm.path,
								type: tar[0]
							})
						}else{
							console.log(cm,'info')
						}
					}
				})
			}else{
				resolve({localPath:'',type: tar[0]})
			}
			
		})
	}))
}

//从接口获取tabbar图标文字，并设置
function setTabbar(done) {
	if(store.state.x_diyStyle){
		uni.setTabBarStyle({
			selectedColor: store.state.x_diyStyle['--color_main'],
		})
	}
	
	request({
		url: 'v3/system/front/setting/getSettings',
		data: {
			names: 'bottom_bar_change_color'
		}
	}).then(res => {
		if (res.state == 200) {
			let bottom_data
			if (res.data && res.data[0]) {
				bottom_data = JSON.parse(res.data[0])
			}
			if (bottom_data) {
				Promise.all([0, 1, 2, 3, 4].map(item => {
					return new Promise((resolve, reject) => {
						let tab = bottom_data.data[item]
						if (tab) {
							// #ifdef APP-PLUS
							getTabImgInfo(tab).then(local => {
								let autoImg = local.find(lo => lo.type == 'autoImg')
								let selectImg = local.find(lo => lo.type =='selectImg')
							// 	uni.setTabBarItem({
							// 		index: item,
							// 		iconPath: autoImg.localPath,
							// 		selectedIconPath: selectImg.localPath,
							// 		text: tab.title,
							// 		complete(com) {
							// 			if (com.errMsg =='setTabBarItem:ok') {
							// 				resolve(tab)
							// 			} else {
							// 				console.log('error')
							// 			}
							// 		}
							// 	})
							// })
							// #endif
							// #ifndef APP-PLUS
							// uni.setTabBarItem({
							// 	index: item,
							// 	iconPath: tab.autoImg.img,
							// 	selectedIconPath: tab.selectImg.img,
							// 	text: tab.title,
							// 	complete(com) {
							// 		resolve(tab)
							// 	}
							// })
							// #endif
						} else {
							resolve()
						}
					})
				})).then(()=>{
					done()
				})
			} else {
				done()
			}
		}else{
			done()
		}
	}).catch(()=>{
		done()
	})
}


//获取接口传来的颜色变量
function getDiyStyle() {
	
	const getSettingsList = Object.values(mappings)
	const color_halo = [
		'--color_halo',
		'--color_integral_halo',
		'--color_extral_halo',
		'--color_spell_halo',
		'--color_presell_halo',
		'--color_ladder_halo',
		'--color_seckill_halo',
		'--color_coupon_halo',
		'--color_video_halo',
	]

	return new Promise((resolve, reject) => {
		request({
			url: 'v3/system/front/setting/getSettings',
			data: {
				names: 'mobile_mall_style,mobile_integral_mall_style,mobile_spreader_mall_style,mobile_spell_mall_style,mobile_presell_mall_style,mobile_ladder_mall_style,mobile_seckill_mall_style,mobile_coupon_mall_style,mobile_video_mall_style'
			}
		}).then(res => {
			if (res.state == 200) {
				if (res.data) {
					let color_set = {}
					res.data.forEach((item, index) => {
						if (item) {
							item = JSON.parse(item)
							for (let i of getSettingsList[index]) {
								color_set[i[0]] = item[i[1]]
								//从各个映射组的主颜色里衍生出一个晕色
								if (i[1] == 'mainColor16' || i[1] == 'mainColor') {
									if (!/rgb.*?/.test(item[i[1]])) {
										color_set[color_halo[index]] = set16ToRgb(item[i[1]], 0.1)
									} else {
										let rgbArr = item[i[1]].match(/((\d{1,3}))/g)
										rgbArr[3] = '0.1'
										color_set[color_halo[index]] =`rgba(${rgbArr.join(',')})`
									}
								} 
							}
						}
					})
					store.commit('saveDiyStyle', color_set)
				}else{
					store.commit('saveDiyStyle', 'ERROR')
				}
			}
			resolve()
		}).catch(err => {
			console.log(err)
			store.commit('saveDiyStyle', 'ERROR')
			reject()
		})
	})
}




export default {
	install(Vue) {
		Vue.mixin(diyStyle_mixins)
		Vue.prototype.$diyStyle = {
			dynaSetTabbar: this.dynaSetTabbar,
			getDiyStyleOnce: this.getDiyStyleOnce,
		}
	},

	dynaSetTabbar() {
		// #ifndef H5
		// uni.hideTabBar()
		// #endif
		const showTab = () => {
			uni.showTabBar()
		}
		setTabbar(showTab)
	},

	getDiyStyleOnce() {
		let once = true
		let _this = this
		if (once) {
			once = false
			return getDiyStyle
		}else{
			return null
		}
	},
}